package com.zzzy.framework.common.dict;


import com.zzzy.common.exception.WarningException;
import com.zzzy.framework.common.annotation.ClassDescription;
import com.zzzy.framework.common.dict.dto.DictData;
import com.zzzy.framework.common.dict.dto.DictInfo;
import com.zzzy.framework.common.enums.DictInterface;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Description: 字段数据接口
 *
 * @author fc
 * @date 2024/6/19
 */
public interface DictInitInterface {

    /**
     * 所有枚举类字典
     * @return
     */
    default List<Class<? extends DictInterface>> getDictEnumClasssList(){
        return Collections.emptyList();
    }

    /**
     * 通过枚举类获取字典数据
     * @return
     */
    default List<DictInfo> getDictInfoFromEnum(){
        List<DictInfo> dictInfoList = new ArrayList<>();
        List<Class<? extends DictInterface>> dictEnumClassList = getDictEnumClasssList();
        for (Class<? extends DictInterface> enumClass : dictEnumClassList) {
            try {
                String enumClassName = enumClass.getSimpleName();
                enumClassName = enumClassName.substring(0, 1).toLowerCase() + enumClassName.substring(1);
                String classDescription = enumClass.getAnnotation(ClassDescription.class).value();

                // 调用values()方法，返回Enum[]数组
                Method valuesMethod = enumClass.getMethod("values");
                DictInterface[] enumConstants = (DictInterface[]) valuesMethod.invoke(null);
                String dictType = enumClassName.replace("Enum", "");
                DictInfo dictInfo = new DictInfo();
                dictInfo.setType(dictType);
                dictInfo.setDescription(classDescription);
                List<DictData> dictDataList = new ArrayList<>();
                for (DictInterface enumConstant : enumConstants) {
                    DictData dictData = new DictData();
                    dictData.setValue(enumConstant.getValue());
                    dictData.setDescription(enumConstant.getDescription());
                    dictDataList.add(dictData);
                }
                dictInfo.setDictDataList(dictDataList);
                dictInfoList.add(dictInfo);
            } catch (Exception e) {
                throw new WarningException("初始化字典枚举错误");
            }
        }
        return dictInfoList;
    }

    /**
     * 通过数据库获取字典数据
     * @return
     */
    default List<DictInfo> getDictInfoFromData(){
        return Collections.emptyList();
    }

    /**
     * 获取全部字典数据
     * @return
     */
    default List<DictInfo> getDictInfoList(){
        List<DictInfo> dictDataFromEnumMap = getDictInfoFromEnum();
        dictDataFromEnumMap.addAll(getDictInfoFromData());
        return dictDataFromEnumMap;
    }
}
